package com.jie.eclipse.pan.editors.assist.contributor;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;

/**
 * jspeditor.assistantContributor扩展点对应的扩展管理器
 *
 * @author zhuxing (mailto:zhu_xing@live.cn)
 */
/*
 * 修改历史
 * $Log$ 
 */
public class AssistantContributorManager {
	private static AssistantContributorManager instance;
	
	private static final String EXTENSION_POINT = "jspeditor.assistantContributor";
	
	private Map<String, AssistantContributorDescriptor> descriptors = new HashMap<String, AssistantContributorDescriptor>();
	
	/**
	 * 标志变量，表征是否加载过
	 */
	private boolean loaded = false;
	
	/**
	 * singleton
	 */
	private AssistantContributorManager() {}
	
	/**
	 * 获取singleton实例
	 * 
	 * @return
	 */
	public static AssistantContributorManager getInstance() {
		if (instance == null) {
			instance = new AssistantContributorManager();
		}
		
		return instance;
	}
	
	/**
	 * 根据唯一标志（标签名或者指令名称）获取对应的IAssistantContributor实例
	 * 
	 * @param id  contributor id
	 * @return
	 */
	public IAssistantContributor getAssistantContributor(String id) {
		if (!this.loaded)
			this.loadExtensions();
		
		AssistantContributorDescriptor descriptor = this.descriptors.get(id);
		if (descriptor == null)
			return null;
		
		return descriptor.createContributor();
	}
	
	/**
	 * 加载"jspeditor.assistantContributor"扩展点对应的扩展
	 */
	private void loadExtensions() {
		if (this.loaded)
			return ;
		
		//从扩展注册表获取扩展，创建中间描述对象并缓存
		IConfigurationElement[] configurationElements = Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT);
		for (int i = 0; i < configurationElements.length; i++) {
			String contributorID = configurationElements[i].getAttribute("id");
			AssistantContributorDescriptor descriptor = new AssistantContributorDescriptor(configurationElements[i]);
			this.descriptors.put(contributorID, descriptor);
		}
		
		//设置标志变量
		this.loaded = true;
	}
	
}
